package com.huawei.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token，不能为空
        String utoken = request.getHeader("U-TOKEN");
        if (!StringUtils.isEmpty(utoken)){
            Object loginTmp = redisTemplate.opsForValue().get(utoken);
            if (loginTmp != null){
                return  true;
            }
        }
        
            response.setContentType("application/jsoncharset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            
            writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;
      
       
    }
}